package com.d.common.interceptor;


import com.d.common.annotation.Login;
import com.d.common.exception.RRException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 权限(Token)验证
 *
 * @author
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    public static final String USER_KEY = "adminId";
    public static final String USER_NAME = "adminName";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;

        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        //获取用户凭证
        String adminId = request.getHeader("X-UserId");

        //凭证为空
        if (StringUtils.isBlank(adminId)) {
            throw new RRException("登录信息为空", HttpStatus.UNAUTHORIZED.value());
        }

        //用户名称
        String adminName ="";
        if(!StringUtils.isBlank(request.getHeader("X-Nickname"))){
            try {
                adminName =URLDecoder.decode(request.getHeader("X-Nickname"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, Long.parseLong(adminId));
        request.setAttribute(USER_NAME, adminName);
        return true;
    }
}
